package com.xiaohao.employee_attendance.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 小浩
 * @date 2019-03-06 21:46
 * @package com.xiaohao.employee_attendance.interceptor
 * @description
 */
public class RemeberIntercepetor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String rememberMe = request.getParameter("rememberMe");
        String autoLogin = request.getParameter("autoLogin");
        System.out.println(rememberMe);
        System.out.println(autoLogin);
        if ("rememberMe".equals(rememberMe)) {
            Cookie username = new Cookie("username", request.getParameter("account"));
            Cookie password = new Cookie("password", request.getParameter("password"));
            response.addCookie(username);
            response.addCookie(password);
        } else {
            for (Cookie cookie : request.getCookies()) {
                if ("username".equals(cookie.getName())) {
                    cookie.setValue("false");
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
                if ("password".equals(cookie.getName())) {
                    cookie.setValue("false");
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        }


        if ("autoLogin".equals(autoLogin)) {
            Cookie username = new Cookie("autoLogin", request.getParameter("autoLogin"));
            response.addCookie(username);
        } else {
            System.out.println("不记住密码");
            for (Cookie cookie : request.getCookies()) {
                if ("autoLogin".equals(cookie.getName())) {
                    System.out.println(cookie.getValue() + "cookie");
                    cookie.setValue("false");
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        }
        return true;
    }
}
